package com.example.manage_dzensaas.service.mq;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.manage_dzensaas.core.constants.FolkMqConstants;
import com.example.manage_dzensaas.core.enums.IdempotentBusinessEnum;
import com.example.manage_dzensaas.core.enums.OrderEnum;
import com.example.manage_dzensaas.filter.exception.CustomException;
import com.example.manage_dzensaas.mapper.db2.ConsumerOrderQxMapper;
import com.example.manage_dzensaas.mapper.db2.IdempotentQueryMapper;
import com.example.manage_dzensaas.pojo.dto.message.CardKeyInfoMeg;
import com.example.manage_dzensaas.pojo.entity.db2.ConsumerOrder;
import com.example.manage_dzensaas.pojo.entity.db2.ConsumerOrderQx;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.folkmq.client.MqConsumeHandler;
import org.noear.folkmq.client.MqMessageReceived;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;
import org.noear.solon.data.tran.TranPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * 回调卡密信息服务
 *
 * @author wangzhiqi
 */
@Component(FolkMqConstants.JD_ORDER_NOTIFY_CARD_KEY_INFO_QUEUE)
public class Service1001Impl implements MqConsumeHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(Service1001Impl.class);

    @Inject
    ServiceCommon serviceCommon;
    @Db("db2")
    IdempotentQueryMapper idempotentQueryMapper;
    @Db("db2")
    ConsumerOrderQxMapper consumerOrderQxMapper;

    @Transaction
    @Override
    public void consume(MqMessageReceived message) {
        try {
            String param = new String(message.getBody(), StandardCharsets.UTF_8);
            LOGGER.info("进入[Service1001Impl execute param]服务: {}", param);

            if (serviceCommon.paramNotNull(param)) {
                returnLogResult(null, "订单入参为空");
            }
            CardKeyInfoMeg cardKeyInfoMeg = JSONObject.parseObject(param, CardKeyInfoMeg.class);
            if (cardKeyInfoMeg == null) {
                returnLogResult(null, "订单入参转换失败");
            }
            if (cardKeyInfoMeg != null && serviceCommon.judgeIdempotence(cardKeyInfoMeg.getOrderId(), IdempotentBusinessEnum.ORDER_BUSINESS_7.getCode())) {
                returnLogResult(cardKeyInfoMeg.getOrderId(), "订单已消费完毕,无需重复消费");
            }
            ConsumerOrder orderInfo = serviceCommon.getOrderInfo(cardKeyInfoMeg.getOrderId());
            if (orderInfo == null) {
                returnLogResult(cardKeyInfoMeg.getOrderId(), "订单不存在");
            }
            if (orderInfo != null && !orderInfo.getOrderType().equals(OrderEnum.ORDER_QX)) {
                returnLogResult(cardKeyInfoMeg.getOrderId(), "订单类型错误,必须是权益订单");
            }
            ConsumerOrderQx qxOrderInfo = serviceCommon.getQxOrderInfo(cardKeyInfoMeg.getOrderId());
            if (qxOrderInfo == null) {
                returnLogResult(cardKeyInfoMeg.getOrderId(), "权益订单不存在");
            }
            if (qxOrderInfo.getProductChannel() != 7) {
                returnLogResult(cardKeyInfoMeg.getOrderId(), "该订单不是自由兑换订单");
            }
            if (qxOrderInfo.getProductKeys() != null) {
                returnLogResult(cardKeyInfoMeg.getOrderId(), "权益订单已处理成功");
            }

            // 更新权益订单
            boolean isExecutionSuccessful = executionSuccess(cardKeyInfoMeg, qxOrderInfo.getId());
            if (!isExecutionSuccessful) {
                executionFail(cardKeyInfoMeg);
                LOGGER.error("[Service1001Impl execute param]服务MQ操作记录更新失败");
            }
        } catch (CustomException e) {
            LOGGER.error("京东回调卡密业务异常：{}", e.getMessage());
        } catch (Exception e) {
            LOGGER.error("京东回调卡密信息服务异常：", e);
        }
    }

    private void returnLogResult(String orderId, String msg) throws RuntimeException {
        LOGGER.error("京东回调卡密信息服务：{} - {}", orderId, msg);
        throw new CustomException(msg);
    }

    @Transaction(policy = TranPolicy.nested)
    private boolean executionSuccess(CardKeyInfoMeg cardKeyInfoMeg, int orderQxId) {
        try {
            if (cardKeyInfoMeg.getCardKeyInfoList() == null || cardKeyInfoMeg.getCardKeyInfoList().isEmpty()) {
                return false;
            }

            ConsumerOrderQx updateEmpty = new ConsumerOrderQx();
            updateEmpty.setProductKeys(JSON.toJSONString(cardKeyInfoMeg.getCardKeyInfoList()));
            updateEmpty.setQxOrderId(cardKeyInfoMeg.getJdOrderId());

            int update = consumerOrderQxMapper.update(
                    updateEmpty,
                    new LambdaUpdateWrapper<ConsumerOrderQx>().eq(ConsumerOrderQx::getId, orderQxId)
            );

            if (update >= 1) {
                idempotentQueryMapper.insertByReq(
                        cardKeyInfoMeg.getOrderId(),
                        IdempotentBusinessEnum.ORDER_BUSINESS_7.getCode(), 1,
                        JSON.toJSONString(cardKeyInfoMeg)
                );
                LOGGER.info("[Service1001Impl execute param]服务MQ操作记录更新成功");
            }
            return update >= 1;
        } catch (Exception e) {
            LOGGER.error("[Service1001Impl execute param]服务权益订单执行操作失败", e);
            return false;
        }
    }

    @Transaction(policy = TranPolicy.nested)
    private void executionFail(CardKeyInfoMeg cardKeyInfoMeg) {
        // 失败请求记录
        idempotentQueryMapper.insertByReq(cardKeyInfoMeg.getOrderId(), IdempotentBusinessEnum.ORDER_BUSINESS_7.getCode(), 2, JSON.toJSONString(cardKeyInfoMeg));
    }
}
